package com.webchat.netty.server.service;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.webchat.common.constants.NettySocketConstants;
import com.webchat.netty.server.config.properties.NacosConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;

@Slf4j
public class NettyNacosRegistry {

    private static NamingService namingService;

    private static NacosConfig NACOS_CONFIG;

    public static void init(NacosConfig nacosConfig) {
        try {
            Properties properties = new Properties();
            properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosConfig.getServerAddr());
            properties.setProperty(PropertyKeyConst.NAMESPACE, nacosConfig.getNamespace());
            namingService = NacosFactory.createNamingService(properties);
            NACOS_CONFIG = nacosConfig;
        } catch (NacosException e) {
            log.error("nacos server connect error. ", e);
        }
    }


    /**
     * 注册服务到nacos注册中心
     *
     * @param serviceName
     * @param ip
     * @param port
     * @param clusterName
     */
    public static void registerInstance(String serviceName, String ip, int port, String clusterName) {

        try {
            namingService.registerInstance(serviceName, NACOS_CONFIG.getGroup(), ip, port, clusterName);
        } catch (NacosException e) {
            log.error("nacos server register instance error. serviceName:{}, ip:{}, port:{}", serviceName, ip, port, e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 销毁Nacos注册服务实例
     *
     * @param serviceName
     * @param ip
     * @param port
     * @param clusterName
     */
    public static void deregisterInstance(String serviceName, String ip, int port, String clusterName) {
        try {
            namingService.deregisterInstance(serviceName, NACOS_CONFIG.getGroup(), ip, port, clusterName);
        } catch (NacosException e) {
            log.error("nacos server deregister instance error. serviceName:{}, ip:{}, port:{}", serviceName, ip, port, e);
            throw new RuntimeException(e);
        }
    }

}
